from PyQt6.QtWidgets import QWidget, QLabel, QVBoxLayout
from PyQt6.QtCore import Qt, QPropertyAnimation, QEasingCurve, QTimer, QRect, QRectF, pyqtProperty
from PyQt6.QtGui import QPainter, QColor, QPainterPath, QFont, QLinearGradient, QPen, QConicalGradient
import win32com.client
import pythoncom

class CircularProgress(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self._progress = 0
        self._hue = 0  # 添加色相值用于动画
        
        # 创建色相动画定时器
        self.color_timer = QTimer(self)
        self.color_timer.timeout.connect(self._update_hue)
        self.color_timer.start(50)  # 每50ms更新一次颜色
        
    def _update_hue(self):
        self._hue = (self._hue + 2) % 360  # 更新色相值
        self.update()  # 触发重绘
        
    def _get_progress(self):
        return self._progress
        
    def _set_progress(self, value):
        self._progress = max(0, min(1, value))
        self.update()
        
    progress = pyqtProperty(float, _get_progress, _set_progress)
    
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.RenderHint.Antialiasing)
        
        # 计算圆环大小和位置
        pen_width = 24
        margin = pen_width / 2
        rect = QRectF(margin, margin, 
                     self.width() - 2 * margin,
                     self.height() - 2 * margin)
        
        # 设置画笔
        pen = QPen()
        pen.setWidth(pen_width)
        pen.setCapStyle(Qt.PenCapStyle.RoundCap)
        
        # 绘制背景圆环
        pen.setColor(QColor(255, 255, 255, 30))
        painter.setPen(pen)
        painter.drawArc(rect.toRect(), 0, 360 * 16)
        
        # 绘制进度圆环
        if self._progress > 0:
            # 创建彩虹渐变
            gradient = QConicalGradient(rect.center(), -90)  # 从顶部开始
            
            # 添加彩虹色渐变
            base_hue = self._hue
            for i in range(0, 360, 40):
                hue = (base_hue + i) % 360
                color = QColor.fromHsv(hue, 200, 250, 255)
                gradient.setColorAt(i / 360.0, color)
            gradient.setColorAt(1.0, QColor.fromHsv(base_hue, 200, 250, 255))
            
            # 设置渐变画笔
            pen.setBrush(gradient)
            painter.setPen(pen)
            
            # 计算角度（Qt使用16倍的角度值）
            start_angle = 90 * 16  # 从顶部开始
            span_angle = int(-self._progress * 360 * 16)  # 转换为整数
            
            painter.drawArc(rect.toRect(), start_angle, span_angle)

class CountdownAlert(QWidget):
    def __init__(self, parent=None, enable_voice=True):
        super().__init__(parent)
        self.enable_voice = enable_voice
        # 只在启用语音时初始化语音引擎
        if self.enable_voice:
            self.init_voice_engine()
        self.initUI()
        
    def init_voice_engine(self):
        # 在新线程中初始化COM
        pythoncom.CoInitialize()
        try:
            self.speaker = win32com.client.Dispatch("SAPI.SpVoice")
            # 设置语音速度 (-10 到 10)
            self.speaker.Rate = 0
            # 设置音量 (0 到 100)
            self.speaker.Volume = 100
        except:
            self.speaker = None
            print("语音引擎初始化失败")
            
    def speak_text(self, text):
        if self.enable_voice and hasattr(self, 'speaker') and self.speaker:
            try:
                self.speaker.Speak(text, 1)  # 1表示异步播放
            except:
                print("语音播放失败")
        
    def initUI(self):
        # 设置窗口属性
        self.setWindowFlags(Qt.WindowType.FramelessWindowHint | 
                          Qt.WindowType.WindowStaysOnTopHint)
        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
        
        # 创建布局
        layout = QVBoxLayout(self)
        layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.setSpacing(0)
        layout.setContentsMargins(0, 0, 0, 0)
        
        # 创建圆形进度条
        self.progress = CircularProgress()
        self.progress.setFixedSize(300, 300)  # 稍微调小一点
        
        # 创建倒计时标签
        self.time_label = QLabel()
        self.time_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.time_label.setStyleSheet("""
            QLabel {
                color: white;
                font-size: 72px;
                font-weight: bold;
                font-family: 'Segoe UI', sans-serif;
            }
        """)
        
        # 创建提示标签
        self.hint_label = QLabel("时间即将结束")
        self.hint_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.hint_label.setStyleSheet("""
            QLabel {
                color: white;
                font-size: 24px;
                font-weight: 300;
                font-family: 'Microsoft YaHei UI Light', 'Segoe UI Light', sans-serif;
                letter-spacing: 2px;
            }
        """)
        
        # 添加部件到布局
        layout.addWidget(self.progress)
        
        # 设置标签的父级为进度条，这样可以显示在圆环中央
        self.time_label.setParent(self.progress)
        self.hint_label.setParent(self.progress)
        
    def resizeEvent(self, event):
        super().resizeEvent(event)
        # 调整标签位置到圆环中央
        progress_rect = self.progress.geometry()
        
        # 调整时间标签位置
        self.time_label.setGeometry(
            0, progress_rect.height() // 2 - 50,
            progress_rect.width(), 100
        )
        
        # 调整提示标签位置
        self.hint_label.setGeometry(
            0, progress_rect.height() // 2 + 30,
            progress_rect.width(), 40
        )
        
    def showEvent(self, event):
        super().showEvent(event)
        screen = self.screen()
        self.setGeometry(screen.geometry())
        
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.RenderHint.Antialiasing)
        
        # 创建径向渐变的背景
        gradient = QLinearGradient(0, 0, self.width(), self.height())
        gradient.setColorAt(0, QColor(0, 0, 0, 200))
        gradient.setColorAt(1, QColor(0, 0, 0, 220))
        painter.fillRect(self.rect(), gradient)
        
    def start_countdown(self, seconds):
        self.remaining_seconds = seconds
        self.update_time_display()
        
        # 播放开始提示音
        self.speak_text("请注意，时间即将结束")
        
        # 设置进度条动画
        self.progress_animation = QPropertyAnimation(self.progress, b"progress")
        self.progress_animation.setDuration(seconds * 1000)
        self.progress_animation.setStartValue(1.0)
        self.progress_animation.setEndValue(0.0)
        self.progress_animation.setEasingCurve(QEasingCurve.Type.Linear)
        
        # 设置定时器
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update_countdown)
        self.timer.start(1000)
        
        # 启动动画
        self.progress_animation.start()
        
    def update_countdown(self):
        self.remaining_seconds -= 1
        if self.remaining_seconds <= 0:
            self.timer.stop()
            # self.speak_text("时间到")
            self.close()
        self.update_time_display()
        
    def update_time_display(self):
        self.time_label.setText(f"{self.remaining_seconds}")
        
    def mousePressEvent(self, event):
        self.close()
        
    def closeEvent(self, event):
        # 关闭时释放COM
        if self.enable_voice and hasattr(self, 'speaker'):
            pythoncom.CoUninitialize()
        super().closeEvent(event) 